package com.rmb.common.exception;

import com.google.common.collect.ImmutableMap;
import com.rmb.common.model.response.CommonCode;
import com.rmb.common.model.response.ResponseResult;
import com.rmb.common.model.response.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wan
 */
@ControllerAdvice
public class ExceptionCatch {

    private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionCatch.class);

    /**
     * 定义map.配置异常类型对应的错误代码
     */
    private static ImmutableMap<Class<? extends Throwable>, ResultCode> EXCEPTIONS;
    /**
     * 定义map的builder对象,去构建ImmutableMap
     */

    private static ImmutableMap.Builder<Class<? extends Throwable>,ResultCode> builder = ImmutableMap.builder();

    /**
     * 捕获CustomException此类异常
     */

    @ExceptionHandler(CustomException.class)
    @ResponseBody
    public ResponseResult customException(CustomException customException){
        //记录日志
        LOGGER.error("catch Exception:{}",customException.getMessage());
        ResultCode resultCode = customException.getResultCode();
        return new ResponseResult(resultCode);
    }

    /**
     * 捕获校验异常
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public ResponseResult handleVaildException(MethodArgumentNotValidException e){
        LOGGER.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult bindingResult = e.getBindingResult();
        Map<String, String> errerMap = new ConcurrentHashMap<>(16);
        StringBuilder errorMessage = new StringBuilder();
        bindingResult.getFieldErrors().forEach(fieldError->{
            errorMessage.append(":").append(fieldError.getDefaultMessage());
        });
        return ResponseResult.methodFail(CommonCode.PARAM_FALL,errorMessage.toString());
    }

    @ExceptionHandler(BindException.class)
    public ResponseResult handleBindException(HttpServletRequest request, BindException exception) {
        List<FieldError> allErrors = exception.getFieldErrors();
        StringBuilder sb = new StringBuilder();
        for (FieldError errorMessage : allErrors) {

        }
        LOGGER.error("cath BindException:{}",exception.getMessage());
        BindingResult bindingResult = exception.getBindingResult();
        return new ResponseResult(CommonCode.valueOf(bindingResult.toString()));
    }

    /**
     * 捕获exception此类异常
     * @param exception
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public ResponseResult exception(Exception exception){
        //记录日志
        LOGGER.error("catch Exception:{}",exception.getMessage());
        if (EXCEPTIONS == null){
            //EXCEPTIONS构建成功,不能更改
            EXCEPTIONS = builder.build();
        }
        //EXCEPTIONS中找异常类型所对应的错误代码,如果找到了将错误代码相应给用户,如果找不到相应99999给用户
        ResultCode resultCode = EXCEPTIONS.get(exception.getClass());
        if (resultCode != null){
            return new ResponseResult(resultCode);
        }else {
            //返回99999异常
            return new ResponseResult(CommonCode.SERVER_ERROR);
        }
    }

    //构建
    static {
        builder.put(HttpMessageNotReadableException.class,CommonCode.INVALID_PARAM);
    }

}
